package ynu.elm.service.impl;

import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ynu.elm.entity.OrderCreationRequest;
import ynu.elm.service.OrdersService;
import ynu.elm.mapper.IOrderDetailetMapper;
import ynu.elm.mapper.ICartMapper;
import ynu.elm.mapper.IOrdersMapper;
import ynu.elm.entity.Orders;
import ynu.elm.entity.OrderDetailet;

import java.util.List;

@Service
public class OrdersServiceImpl implements OrdersService {

    @Resource
    private IOrdersMapper ordersMapper;

    @Resource
    private IOrderDetailetMapper orderDetailetMapper;

    @Resource
    private ICartMapper cartMapper;

    @Override
    @Transactional
    public int createOrders(OrderCreationRequest request) {
        Orders orders = new Orders();
        orders.setUserId(request.getUserId());
        orders.setBusinessId(request.getBusinessId());
        orders.setDaId(request.getDaId());
        orders.setOrderTotal(request.getOrderTotal());
        orders.setOrderState(0); // 初始订单状态为0（待支付）

        // 创建订单（返回生成的订单编号）
        int saved = ordersMapper.saveOrders(orders);
        if (saved == 0) {
            throw new RuntimeException("订单保存失败");
        }
        int orderId = orders.getOrderId();

        // 保存订单明细
        if (request.getList() != null && !request.getList().isEmpty()) {
            for (OrderDetailet detailetDto : request.getList()) {
                OrderDetailet detail = new OrderDetailet();
                detail.setFoodId(detailetDto.getFoodId());
                detail.setQuantity(detailetDto.getQuantity());
                detail.setOrderId(orderId); //
                orderDetailetMapper.saveOrderDetailetBatch(detail);
            }
        }
        cartMapper.deleteByUserIdAndBusinessId(request.getUserId(), request.getBusinessId());


        return orderId;
    }

    @Override
    public Orders getOrdersById(Integer orderId){
        Orders orders = ordersMapper.getOrdersById(orderId);
        if (orders != null) {
            orders.setList(orderDetailetMapper.listOrderDetailetByOrderId(orderId));
        }
        return orders;
    }

    @Override
    public List<Orders> listOrdersByUserId(String userId){
        List<Orders> ordersList = ordersMapper.listOrdersByUserId(userId);
        if (ordersList != null) {
            for (Orders order : ordersList) {
                if (order.getList() == null || order.getList().isEmpty()) {
                    order.setList(orderDetailetMapper.listOrderDetailetByOrderId(order.getOrderId()));
                }
            }
        }
        return ordersList;
    }

    @Override
    public int updateOrder(Orders orders) {
        return ordersMapper.update(orders);
    }
}